<template>
  <div class="login">
    <!--登录框-->
    <div class="login_box">
      <!--图像-->
      <div class="avater">
        <img src="../assets/img/logo.jpg" alt="">
      </div>
      <!--表单-->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名" prefix-icon="el-icon-s-custom"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="ruleForm.password" placeholder="请输入密码"
                    prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      ruleForm: { /*绑定表单数据*/
        username: 'admin',
        password: '123456',
      },
      rules: {/*验证规则*/
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const {data: res} = await this.$axios.post('admin/login', this.ruleForm)
          console.log(res);
          if (res.code == '0') {
            this.$message.success("登录成功")
            this.$store.commit("addLoginUser", this.ruleForm.username)
            window.localStorage.setItem("userInfo",this.ruleForm.username)
            /*存储在本地jwt--token*/
            window.sessionStorage.setItem("token", res.data)
            return this.$router.push("/home")
          } else {
            this.$message.error("登录失败")
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.login {
  background: #EEC591;
  height: 100%;
}

.login_box {
  width: 400px;
  height: 300px;
  background: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 8px;
}

.avater {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 1px solid #EEAD0E;
  padding: 10px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
}

.avater img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.el-form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
}

.btns {
  display: flex;
  justify-content: flex-end;
}
</style>